import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Upload, Button } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import axios from 'axios';
import { message } from 'antd';
import styles from './index.less';

const Uploader = ({
  value,
  onChange = (data: any) => {},
  showList = true,
  url = '/api/file/v1/upload',
  disabled = false,
}) => {
  let [Files, setFiles] = useState([]);
  const [loading, setloading] = useState(false);
  useEffect(() => {
    value && setFiles(value);
    return () => {
      setFiles([]);
    };
  }, [value]);

  const fileChange = data => {
    if (!loading) {
      message.loading({ content: '文件上传中，请稍后...', key: 'updatable' });
      setloading(true);
    }
    const { file, fileList, event } = data;
    console.log('-- upload percent --', file.percent);
    if (file.response) {
      Files = Files.concat(file.response.data);
      // fileList.map(item => {
      //   let detail = item.response;
      //   list = list.concat(detail.data);
      // });
      onChange(Files);
      setFiles(Files);
      setloading(false);
      message.success({ content: '上传成功', key: 'updatable', duration: 2 });
    }
  };
  const download = ({ uuid, name }) => {
    axios({
      url: `/api/file/v1/download?uuid=${uuid}`,
      method: 'get',
      data,
      responseType: 'arraybuffer',
      headers: {
        token: sessionStorage.getItem('token'),
      },
    })
      .then(res => {
        let blob = new Blob([res.data]);
        let link = document.createElement('a');
        let fileName = name;
        link.href = window.URL.createObjectURL(blob);
        link.download = decodeURIComponent(fileName);
        link.click();
      })
      .catch(() => {
        console.log('下载异常');
      });
  };
  const deleteImg = index => {
    Files.splice(index, 1);
    setFiles([...Files]);
    onChange([...Files]);
  };

  const beforeUpload = file => {
    const allow = [
      'xlsx',
      'xls',
      'docx',
      'doc',
      'pdf',
      'png',
      'jpg',
      'jpeg',
      'bmp',
      'ppt',
      'pptx',
    ];
    const type = file.name.split('.').pop();
    if (allow.indexOf(type) < 0) {
      message.error('只允许上传EXCEL, WORD, PDF, IMAGE, PPT文件');
      return false;
    }
    return true;
  };
  return (
    <div>
      <Upload
        disabled={disabled}
        name="files"
        showUploadList={false}
        action={url}
        headers={{ token: sessionStorage.getItem('token') }}
        onChange={data => fileChange(data)}
        beforeUpload={file => beforeUpload(file)}
      >
        {Files.length >= 8 ? null : (
          <Button type="primary" disabled={disabled}>
            上传文件
          </Button>
        )}
      </Upload>
      {showList &&
        Files &&
        Files.map((item, index) => (
          <div className={styles.file} key={index}>
            <DeleteOutlined onClick={() => deleteImg(index)} />
            <Button
              className={styles.filename}
              type="link"
              onClick={() => download(item)}
              disabled={loading || disabled}
            >
              {item.name}
            </Button>
          </div>
        ))}
    </div>
  );
};
export default connect(state => state.base)(Uploader);
